package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.rpc.IMemberService;
import com.pms.service.*;
import com.pms.util.DaHaoLockUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 门锁信息修改，只能修改锁信息
 */
@RestController
@RequestMapping("estatedoorLockBase")
@Api(value="门锁管理",description = "门锁管理界面接口")
public class EstateDoorLockController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IEntranceDoorService entranceDoorService;
    @Autowired
    private IEstateDoorLockService estateDoorLockService;
    @Autowired
    private IEstateEqFactoryService estateEqFactoryService;
    @Autowired
    private IEstateAgencyService agencyService;
    @Autowired
    IEstateDoorCardService estateDoorCardService;
    @Autowired
    private DaHaoLockUtil daHaoLockUtil;
    @Autowired
    IEstateLockCardService estateLockCardService;
    @ApiOperation(value = "绑定门锁-智果锁")
    @RequestMapping(value = "/bindLockToDoor",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="eqSn",value="设备序列号",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqName",value="设备名称",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqKey",value="设备密钥(偏向键值)",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="factoryServiceUrl",value="设备服务url(偏向地址路径)",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqTypeFactory",value="设备类型",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="eqMac",value="设备mac地址",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="factoryCode",value="设备所属厂商编号(后台给予,默认zhiGuo)",required = false,dataType = "string",paramType="form"),
    })
    public R bindLockToDoor(String eqSn, String eqName, String eqKey, String eqMac,String factoryServiceUrl
            ,Integer eqTypeFactory , String factoryCode, Long doorId) {
        parameterIsBlank(eqSn,"请填写设备序列号");
        parameterIsBlank(eqName,"请填写设备名称");
        parameterIsBlank(eqKey,"请填写偏向键值");
        parameterIsNull(eqTypeFactory,"请填写设备类型");
        parameterIsBlank(eqMac,"请填写设备mac地址");
        parameterIsNull(doorId,"请选择设备关联的门");
        EntranceDoor door = entranceDoorService.selectById(doorId);
        parameterIsNull(door,"未查询到门信息");
        if(door.getIsHaveLock()!=null&&door.getIsHaveLock()==1){
            return R.error(400,"该门已绑定设备");
        }
        if(StringUtils.isBlank(factoryCode)){
            factoryCode = "zhiGuo";// 默认智果设备id
        }
        EstateAgency community = agencyService.selectById(door.getCommunityId());
        parameterIsNull(community,"未查询到门对应的社区信息");
        EstateEqFactory  eqFactory = estateEqFactoryService.selectOne(new EntityWrapper<EstateEqFactory>().eq("factory_code",factoryCode));
        parameterIsNull(eqFactory,"未查询厂商信息");
        if(eqFactory.getFactoryType()!=2){
            return R.error(400,"厂商类型错误");
        }
        if(StringUtils.isBlank(factoryServiceUrl)){
            factoryServiceUrl = eqFactory.getFactoryServiceUrl();
        }
        EstateDoorLock insertDoorLock = new EstateDoorLock();
        insertDoorLock.setDoorType(door.getDoorType());
        insertDoorLock.setDoorName(door.getDoorName());
        insertDoorLock.setDoorId(door.getDoorId());
        insertDoorLock.setUnitId(door.getUnitId());
        insertDoorLock.setConmunityId(door.getCommunityId());
        insertDoorLock.setConmunityName(community.getAgencyName());
        insertDoorLock.setAgencyId(door.getAgencyId());
        insertDoorLock.setFactoryCode(factoryCode);//设置厂商
        insertDoorLock.setEqKey(eqKey);
        insertDoorLock.setEqName(eqName);
        insertDoorLock.setEqSn(eqSn);
        insertDoorLock.setEqMac(eqMac);
        insertDoorLock.setEqTypeFactory(eqTypeFactory);
        insertDoorLock.setFactoryServiceUrl(factoryServiceUrl);
        insertDoorLock.setEqPswd("");
        insertDoorLock.setPswdValidTime(null);
        insertDoorLock.setEqInputPswd("");
        insertDoorLock.setCreateTime(new Date());
        estateDoorLockService.insert(insertDoorLock);
        EntranceDoor entranceDoor = new EntranceDoor();
        entranceDoor.setIsHaveLock(1);//修改门状态为  已绑定设备
        entranceDoorService.update(entranceDoor,new EntityWrapper<EntranceDoor>().eq("door_id",doorId));
        return R.ok();
    }

    @ApiOperation(value = "分页查询锁设备使用情况")
    @RequestMapping(value = "/readPage",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",value="请求条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="请求页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="conmunityId",value="小区id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitId",value="单元id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="doorType",value="门类型:1-大门,2-单元门,3-车库门,默认查所有",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="factoryCode",value="厂商编号",required = false,dataType = "string",paramType="form"),
    })
    public  R readPage(Long conmunityId,Long unitId,Integer doorType,String factoryCode,Integer pageSize,Integer pageNum){
        if(null==pageNum||pageNum<1){pageNum=1;}
        if(null==pageSize||pageSize<1){pageSize=10;}
        parameterIsNull(conmunityId,"社区id不能为空");
        Page<EstateDoorLock> page = new Page<EstateDoorLock>(pageNum,pageSize);
        Wrapper<EstateDoorLock> wp = new EntityWrapper<EstateDoorLock>();
        wp.eq("conmunity_id",conmunityId);
        if(doorType!=null){
            wp.eq("door_type",doorType);
        }
        if(unitId!=null){
            if(doorType!=null&&doorType!=1){
                wp.eq("unit_id",unitId);
            }
        }
        if(StringUtils.isNotBlank(factoryCode)){
            wp.eq("factory_code",factoryCode);
        }
        Page<EstateDoorLock> dataPage = estateDoorLockService.selectPage(page,wp);
        return R.ok().put("data",dataPage).putMpPageDescription().putDescription(EstateDoorLock.class);
    }
    @ApiOperation(value = "查询锁设备使用情况")
    @RequestMapping(value = "/readList",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="conmunityId",value="小区id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitId",value="单元id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="doorType",value="门类型:1-大门,2-单元门,3-车库门,默认查所有",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="factoryCode",value="厂商编号",required = false,dataType = "string",paramType="form"),
    })
    public  R readList(Long conmunityId,Long unitId,Integer doorType,String factoryCode){
        parameterIsNull(conmunityId,"社区id不能为空");
        Wrapper<EstateDoorLock> wp = new EntityWrapper<EstateDoorLock>();
        wp.eq("conmunity_id",conmunityId);
        if(doorType!=null){
            wp.eq("door_type",doorType);
        }
        if(unitId!=null){
            if(doorType!=null&&doorType!=1){
                wp.eq("unit_id",unitId);
            }
        }
        if(StringUtils.isNotBlank(factoryCode)){
            wp.eq("factory_code",factoryCode);
        }
        List<EstateDoorLock> dataPage = estateDoorLockService.selectList(wp);
        return R.ok().put("data",dataPage).putDescription(EstateDoorLock.class);
    }
    @ApiOperation(value = "解除门锁绑定")
    @RequestMapping(value = "/removeLockToDoor",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="eqSn",value="设备序列号",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="doorId",value="门id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="userId",value="用户id",required = false,dataType = "long",paramType="form"),
    })
    public R removeLockToDoor(String eqSn,Long doorId) {
        parameterIsBlank(eqSn,"设备序列号不能为空");
        parameterIsNull(doorId,"请选择绑定的门");
        Wrapper<EstateDoorLock> doorLockWp= new EntityWrapper<EstateDoorLock>();
        doorLockWp.eq("eq_sn",eqSn);
        doorLockWp.eq("door_id",doorId);
        EstateDoorLock estateDoorLock =estateDoorLockService.selectOne(doorLockWp);
        parameterIsNull(estateDoorLock,"未查询到相关门锁信息");
        /**
         * 验证用户权限
         */
        estateDoorLockService.deleteById(estateDoorLock.getLockId());
        EntranceDoor entranceDoor = new EntranceDoor();
        entranceDoor.setIsHaveLock(2);//修改门状态为  未绑定设备
        entranceDoorService.update(entranceDoor,new EntityWrapper<EntranceDoor>().eq("door_id",doorId));
        // 同步删除 设备的卡片下发记录
        estateDoorCardService.delete(new EntityWrapper<EstateDoorCard>().eq("door_id",doorId));
        estateLockCardService.delete(new EntityWrapper<EstateLockCard>().eq("door_id",doorId));
        return R.ok();
    }

    @ApiOperation(value = "查询门锁信息")
    @RequestMapping(value = "/readInfo",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="lockId",value="门锁id",required = true,dataType = "long",paramType="form"),
    })
    public R readInfo(Long lockId) {
        parameterIsNull(lockId,"门锁id不能为空");
        EstateDoorLock oldDoorLock = estateDoorLockService.selectById(lockId);
        parameterIsNull(oldDoorLock,"未查询到门锁信息");
        return R.ok().put("data",oldDoorLock).putDescription(EstateDoorLock.class);
    }

    @ApiOperation(value = "修改门锁信息-智果锁")
    @RequestMapping(value = "/editDoorLock",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="lockId",value="门锁id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="eqSn",value="设备序列号",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqName",value="设备名称",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqKey",value="设备密钥(偏向键值)",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="factoryServiceUrl",value="设备服务url(偏向地址路径)",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="eqTypeFactory",value="设备类型",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="eqMac",value="设备mac地址",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="userId",value="用户id",required = false,dataType = "long",paramType="form"),
    })
    public R editDoorLock(Long lockId,String eqSn, String eqName, String eqKey, String eqMac,String factoryServiceUrl,Integer eqTypeFactory) {
        parameterIsBlank(eqSn,"请填写设备序列号");
        parameterIsBlank(eqName,"请填写设备名称");
        parameterIsBlank(eqKey,"请填写偏向键值");
        parameterIsNull(eqTypeFactory,"请填写设备类型");
        parameterIsBlank(eqMac,"请填写设备mac地址");
        EstateDoorLock insertDoorLock = estateDoorLockService.selectById(lockId);
        parameterIsNull(insertDoorLock,"未查询到门锁信息");
        boolean editTag = false;
        if(StringUtils.isNotBlank(factoryServiceUrl)){
            if(! insertDoorLock.getFactoryServiceUrl().equals(factoryServiceUrl)){
                insertDoorLock.setFactoryServiceUrl(factoryServiceUrl);
                editTag = true;
            }
        }
        if(StringUtils.isNotBlank(eqSn)){
            if(! insertDoorLock.getEqSn().equals(eqSn)){
                insertDoorLock.setEqSn(eqSn);
                editTag = true;
            }
        }
        if(StringUtils.isNotBlank(eqName)){
            if(! insertDoorLock.getEqName().equals(eqName)){
                insertDoorLock.setEqName(eqName);
                editTag = true;
            }
        }
        if(StringUtils.isNotBlank(eqKey)){
            if(! insertDoorLock.getEqKey().equals(eqKey)){
                insertDoorLock.setEqKey(eqKey);
                editTag = true;
            }
        }
        if(StringUtils.isNotBlank(eqMac)){
            if(! insertDoorLock.getEqMac().equals(eqMac)){
                insertDoorLock.setEqMac(eqMac);
                editTag = true;
            }
        }
        if(eqTypeFactory!=null){
            if(! insertDoorLock.getEqTypeFactory().equals(eqTypeFactory)){
                insertDoorLock.setEqTypeFactory(eqTypeFactory);
                editTag = true;
            }
        }
        if(editTag){
            /**
             * 验证用户权限
             */
            estateDoorLockService.updateById(insertDoorLock);
        };
        return R.ok();
    }

    @ApiOperation(value = "查询设备是否在线")
    @RequestMapping(value = "/readLockIsOnLine",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="doorId",value="门id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="eqSn",value="设备id",required = false,dataType = "string",paramType="form"),
    })
    public R readLockIsOnLine(String eqSn,Long doorId){
        if(org.apache.commons.lang3.StringUtils.isBlank(eqSn)){
            eqSn=null;
            if(doorId==null){
                return  R.error(400,"参数不能为空");
            }
        }
        Map<String,Object> map = daHaoLockUtil.checkDeviceIsOnLine(eqSn,doorId);
        if(map==null){
            return  R.error(400,"未查询到设备信息");
        }
        return R.ok().put("data",map.get("isOnLine")).putDescription("{true:在线,false:不在线},");
    }
}